﻿package com.toncen.samepms.basic.dao;

import java.util.ArrayList;
import java.util.List;

import com.toncen.samepms.basic.domain.User;
import com.toncen.samepms.basic.domain.UserRole;
import com.toncen.samepms.common.AbstractDao;
import com.toncen.samepms.system.domain.Role;

/**
 * 描述：用户表BASIC_USER的dao文件
 * 
 * @author tch
 */
public class UserDao<U> extends AbstractDao<User> {

	public UserDao() {
	}

	@Override
	public long add(User domain) throws Exception {
		long id = super.add(domain);
		UserRoleDao userRoleDao = new UserRoleDao();
		List<UserRole> userRoles = new ArrayList<UserRole>();

		List<Role> roles = domain.getRoles();
		for (Role role : roles) {
			UserRole userRole = new UserRole();
			userRole.setUser(domain);
			userRole.setRole(role);
			userRoles.add(userRole);
		}
		userRoleDao.add(userRoles);

		return id;
	}

	@Override
	public int update(User domain) throws Exception {
		for (Role role : domain.getRoles()) {// 防止延迟加载没有加载就删除了
			role.getName();
		}
		User oldDomain = find(domain);
		if (oldDomain != null) {
			UserRoleDao userRoleDao = new UserRoleDao();
			userRoleDao.deleteByUserId(domain.getId());

			List<UserRole> userRoles = new ArrayList<UserRole>();

			List<Role> roles = domain.getRoles();
			for (Role role : roles) {
				UserRole userRole = new UserRole();
				userRole.setUser(domain);
				userRole.setRole(role);
				userRoles.add(userRole);
				userRoleDao.save(userRole);
			}
		}
		return super.update(domain);

	}

	@Override
	public int delete(long id) throws Exception {
		UserRoleDao userRoleDao = new UserRoleDao();
		userRoleDao.deleteByUserId(id);
		return super.delete(id);
	}

	/**
	 * @param state
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public List<User> getByAccount(String account) throws Exception {
		return findList("getByAccount", account);
	}

	@SuppressWarnings("unchecked")
	public List<User> getByIds(String account) throws Exception {
		return getSqlMap().queryForList(getStatement("getByIds"), account);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.comit.common.db.BaseDao#initialize()
	 */
	@Override
	protected void initialize() {
		setStatementPrefix("User");
		setStatementDivision(".");
	}

	/**
	 * 获取全部用户
	 * 
	 * @param exclude
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public List<User> getAllUserExclude() throws Exception {
		return (List) findList("getAllUserExclude", null);
	}

	/**
	 * @param user
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public List<User> getForgotUser(User user) throws Exception {
		return (List) findList("getForgotUser", user);
	}
}
